package com.uzai.console.service.rocketmq.impl;

import com.alibaba.fastjson.JSONObject;
import com.uzai.common.utils.MqTopics;
import com.uzai.console.common.utils.Tools;
import com.uzai.console.service.rocketmq.FdSendMsgProducerService;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.support.MessageBuilder;
import org.springframework.stereotype.Service;

/**
 * @Auther: liuqi
 * @Date: 2021/11/15 14:45
 * @Description:
 */
@Service
public class FdSendMsgProducerServiceImpl implements FdSendMsgProducerService {
    private static Logger logger = LoggerFactory.getLogger(FdSendMsgProducerServiceImpl.class);

    @Autowired
    private RocketMQTemplate rocketMQTemplate;
    private static final int TOTAL_RETRY = 2;

    /**
     * 发送发单子任务id
     * @author jitwxs
     * @date 2021/11/30 17:09
     * @param childJobId
     */
    @Override
    public void pushFdSendJob(Long childJobId, int retry) {
        String msg = Tools.getStrEmpty(JSONObject.toJSONString(childJobId));
        logger.info("发送发单消息时，推送MQ的子任务id，msg:{}",msg);
        if (retry < TOTAL_RETRY){
            try {
                SendResult sendResult = rocketMQTemplate.syncSend(MqTopics.FD_SEND_JOB, MessageBuilder.withPayload(String.valueOf(childJobId)).build(),3000,10);
                logger.info("{}::{}",new Object[]{childJobId,sendResult.getMsgId()});
            } catch (Exception e) {
                logger.error("err:",e);
                retry = retry+1;
                pushFdSendJob(childJobId, retry);
            }

        }else {
            logger.info("retry fail:{}",msg);
        }
    }
}
